/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mensajes;


import herramientas.baseDatos;
import java.io.*;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
 *
 * @author Usuario
 */
public class ComponerMensajeAction extends org.apache.struts.action.Action {

    /*
     * forward name="success" path=""
     */
    private static final String SUCCESS = "success";
    private final static String FAILURE = "failure";
    private final static String INVALIDU = "invalidU";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ComponerMensajeForm formBean = (ComponerMensajeForm) form;        
        
        baseDatos bd = baseDatos.getInstance();
        String s;
        if (formBean.getUniversidad().equals("falso")){
            String s1 = bd.getUserId(formBean.getDestinatario());
            if (s1==null){
                int er = 1;
                request.setAttribute("error", "destinatario");
                request.setAttribute("ddestinatario", "error");
                return mapping.findForward(FAILURE);        
            }
            
            
            String rutaApp = this.getServlet().getServletContext().getRealPath("/") ;
            FormFile myFile = formBean.getFile();
            String remitente = formBean.getRemitenteId();
            String username = bd.UsuarioGetUsername(remitente);
            int tamano = myFile.getFileSize();
            String tipo = myFile.getContentType();
            if (tamano > 10485760){
                request.setAttribute("error", "tamano");
                return mapping.findForward(FAILURE);
            }
            if (tipo.equals("application/x-msdownload")){
                request.setAttribute("error", "tipo");
                return mapping.findForward(FAILURE);
            }
            System.out.println(tamano);
            byte[] datoss = myFile.getFileData();
            Random randomGenerator = new Random();  
            int randomInt = randomGenerator.nextInt(100000);        
            String titulo = new String(myFile.getFileName().getBytes("ISO-8859-1"), "UTF-8");
            String path = rutaApp + "archivos\\" +username + "\\" +randomInt + "\\" +titulo;
            File saveFile = new File(path);
            saveFile.getParentFile().mkdirs();
            FileOutputStream fOutput = new FileOutputStream(saveFile);
            DataOutputStream out = new DataOutputStream(fOutput);
            out.write(datoss);
            
             out.close();             
             bd.agregarArchivo(path);

            s = bd.MensajesEnviar(formBean,false,path);
            if (s!=null){
                
                String destinatario = formBean.getDestinatario();
                String[] datos =bd.obtenerInfoUsuario(destinatario);
                String nombre = bd.MensajesGetNombreUsuario(datos[1]);
                String email = datos[0].substring(0,(datos[0].length()-1));	    
                herramientas.notificar.notificarMensaje(nombre,email);
                baseDatos.cerrarConexion();
                return mapping.findForward(SUCCESS);        
            }    
            else{
                baseDatos.cerrarConexion();
                request.setAttribute("error", "campos");                
                return mapping.findForward(FAILURE);        
            }    
         }else{
                List a1 = bd.getUsuariosUniversidadQuery(formBean.getUniversidad());
                for (int i = 0; i < a1.size(); i++) {
                    String s1 = (String) a1.get(i);
                    formBean.setDestinatario(s1);
                    s = bd.MensajesEnviar(formBean, true, "");
                    if (s!=null){
                        String destinatario = formBean.getDestinatario();
                        String username = bd.UsuarioGetUsername(destinatario);
                        String[] datos =bd.obtenerInfoUsuario(username);
                        String nombre = bd.MensajesGetNombreUsuario(destinatario);
                        String email = datos[0].substring(0,(datos[0].length()-1));	    
                        herramientas.notificar.notificarMensaje(nombre,email);     
                    }    
                    else{
                        baseDatos.cerrarConexion();
                        return mapping.findForward(FAILURE);        
                    }
                }
                bd.EnviarMasivo(formBean);    
                return mapping.findForward(SUCCESS);
        }
   }
}
